from conan import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake, cmake_layout,CMakeDeps
from conan.tools.files import copy, get,chdir
from conan.tools.gnu import Autotools, AutotoolsToolchain
import os
class SampleRecipe(ConanFile):
    name = "sqilte"
    version = "3.45"
    license = "{{ license }}"  # Example: "MIT"
    author = "{{ author }}"  # Example: "Gabriel Melman"
    url = "{{ url }}"  # Example: "https://github.com/gabime/spdlog"
    description = "{{ description }}"  # Example: "Fast C++ logging library."
    topics = ("{{ topics }}")  # Example: ("C++", "logging", "library", "spdlog")
    settings = "os", "compiler", "build_type", "arch"  # Standard settings
    options = {"shared": [True, False], "fPIC": [True, False],"usr_mode" : ["cmake", "autotools"]}  # options of the package
    default_options = {"shared": False, "fPIC": True , "usr_mode" : "cmake"}  # default options of the package


    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.build_mode = "cmake"   
        self.work_dir = "" # 用于指定CMakeLists.txt所在的目录
    def source(self):# source of the package
    #     # Please, be aware that using the head of the branch instead of an immutable tag
    #     # or commit is a bad practice and not allowed by Conan
        get(self, "https://github.com/sqlite/sqlite/archive/refs/tags/version-3.45.2.zip",
                  strip_root=True)
        self.output.info("self.source_folder" + self.source_folder)
        #self.work_dir = os.path.join(self.source_folder, "subfolder")
    # def requirements(self):
    #     self.requires("libiconv/1.17")

    def config_options(self):
        if self.settings.os == "Windows":
            del self.options.fPIC # Windows does not require -fPIC flag

    def layout(self):
        cmake_layout(self)

    def generate(self):# third step
        self.detect_build_system()
        self.output.info("generate pwd = " + os.getcwd())
        if self.build_mode == "cmake":
            tc = CMakeToolchain(self)
            tc.generate()
            tc.variables["BUILD_SHARED_LIBS"] = "ON" if self.options.shared else "OFF"
            if self.settings.os != "Windows":
                tc.variables["CMAKE_POSITION_INDEPENDENT_CODE"] = "ON" if self.options.fPIC else "OFF"
            deps = CMakeDeps(self)
            deps.generate()
        elif self.build_mode == "autotools":
            tc = AutotoolsToolchain(self)
            tc.generate()
        else:
            raise Exception("No build system found. Please provide a CMakeLists.txt or a configure script.")


    def build(self):
        self.output.info(" build pwd = " + os.getcwd())    
        if self.build_mode == "cmake":
            self.output.info("执行 CMake 构建流程")
            cmake = CMake(self)
            # toolchain_path = os.path.join(self.build_folder,"generators","conan_toolchain.cmake")
            # # 验证路径是否存在
            # if not os.path.exists(toolchain_path):
            #     self.output.error("Specified toolchain file does not exist: " + toolchain_path)
            #     raise Exception("Toolchain file not found")
            # self.output.info("toolchain_path = " + toolchain_path) 

            # conanbuild_sh_path = os.path.join(self.build_folder, "generators", "conanbuild.sh")
            # if os.path.exists(conanbuild_sh_path):
            #     self.run(f"bash -c 'source {conanbuild_sh_path}'", cwd=self.build_folder)
            # else:
            #     self.output.error(f"conanbuild.sh does not exist: {conanbuild_sh_path}")
            #     raise Exception("conanbuild.sh not found")

            # cmake.configure(variables={"CMAKE_TOOLCHAIN_FILE": toolchain_path})
            if self.work_dir:
                cmake.configure(build_script_folder=self.work_dir)
            else:
                cmake.configure()
            cmake.build()
        elif self.build_mode == "autotools":    
            with chdir(self, self.source_folder):
                self.output.info("执行 Autotools 构建流程")
                self.output.info("package_folder = " + self.package_folder)
                autotools = Autotools(self)
                autotools.configure(args=["--prefix={}".format(self.package_folder)])
                autotools.make()    
    def package(self):
        self.output.info(" package pwd = " + os.getcwd())    
        if self.build_mode == "cmake":
            cmake = CMake(self)
            cmake.install()
        elif self.build_mode == "autotools":  
            with chdir(self, self.source_folder):
                autotools = Autotools(self)
                autotools.install()
        else:
            self.output.error("build_mode = " + self.build_mode)
    def package_info(self):
        self.cpp_info.libs = ["Sample"] # Example: ["spdlog"]
    def detect_build_system(self):
        cmake_file_path = os.path.join(self.source_folder, "CMakeLists.txt")
        
        if os.path.exists(cmake_file_path):
            self.output.info("CMakeLists.txt exists: Yes")
        elif os.path.exists(os.path.join(self.source_folder, "configure")):
            self.build_mode = "autotools"
            self.output.info("configure exists: Yes")
            # 如果不加权限,configure()方法有可能无法执行
            os.chmod(os.path.join(self.source_folder, "configure"), 0o755)
        else: #目前只处理 CMakeLists.txt 和 configure
            self.output.error("CMakeLists.txt exists: No")
            self.output.error("configure exists: No")
            self.build_mode = str(self.options.usr_mode)
            self.output.info("build_mode = " + self.build_mode)
            # raise Exception("No build system found. Please provide a CMakeLists.txt or a configure script.")   